package coder.nav.utils;

import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * Markdown渲染样式优化
 * @author Bosen 2025/5/30 11:19
 */
public class MdStyleUtils {

    public static String markdownToStyledHtml(String markdown) {
        return markdownToStyledHtml("", markdown);
    }

    public static String markdownToStyledHtml(String title, String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);

        HtmlRenderer renderer = HtmlRenderer.builder()
                .attributeProviderFactory(context -> new MarkdownAttributeProvider())
                .build();

        String htmlContent = renderer.render(document);

        return wrapWithHtmlTemplate(title, htmlContent);
    }

    private static String wrapWithHtmlTemplate(String title, String content) {
        return "<html>"
                + "<head>"
                + "<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'>"
                + "<title>" + title + "</title>"
                + "</head>"
                + "<style>" + getDefaultCss() + "</style>"
                + "<body>"
                + "<div class='markdown-content'>" + content + "</div>"
                + "</body>"
                + "</html>";
    }

    private static String getDefaultCss() {
        ClassLoader classLoader = MdStyleUtils.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("static/css/markdown/style.css");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while(true) {
            try {
                if ((line = br.readLine()) == null) break;
            } catch (IOException ignored) {}
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    static class MarkdownAttributeProvider implements AttributeProvider {
        @Override
        public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
            if (node instanceof Heading) {
                attributes.put("class", "markdown-heading markdown-" + tagName);
            } else if (node instanceof Paragraph) {
                attributes.put("class", "markdown-paragraph");
            } else if (node instanceof Link) {
                attributes.put("class", "markdown-link");
            } else if (node instanceof Code) {
                attributes.put("class", "markdown-inline-code");
            } else if (node instanceof BlockQuote) {
                attributes.put("class", "markdown-blockquote");
            }
        }
    }

}
